<template>
  <div class="inventory-balance">
    <!-- 页面标题和搜索区域 -->
    <div class="page-header">
      <div class="title-section">
        <h2 class="page-title">库存余额</h2>
      </div>
      
      <div class="search-section">
        <el-input
          v-model="searchForm.productCode"
          placeholder="产品编码"
          class="search-input"
          clearable
        />
        <el-button type="primary" @click="handleSearch" class="search-btn">
          查询
        </el-button>
        <el-button type="primary" @click="showAdvancedSearch = !showAdvancedSearch" class="advanced-btn">
          {{ showAdvancedSearch ? '收起' : '高级查询' }}
        </el-button>
        <el-button class="view-toggle-btn" @click="showColumnSettings = !showColumnSettings">
          <el-icon><Grid /></el-icon>
          列表设置
        </el-button>
      </div>
    </div>

    <!-- 高级查询表单 -->
    <div v-show="showAdvancedSearch" class="advanced-search-section">
      <el-form :model="advancedSearchForm" label-width="100px" class="advanced-search-form">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="产品编码">
              <el-input v-model="advancedSearchForm.productCode" placeholder="产品编码" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="产品名称">
              <el-input v-model="advancedSearchForm.productName" placeholder="产品名称" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="产品规格">
              <el-input v-model="advancedSearchForm.productSpec" placeholder="产品规格" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="库存数量">
              <el-input v-model="advancedSearchForm.inventoryQuantity" placeholder="库存数量" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="库存单位">
              <el-input v-model="advancedSearchForm.inventoryUnit" placeholder="库存单位" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="最大库存">
              <el-input v-model="advancedSearchForm.maxInventory" placeholder="最大库存" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="最小库存">
              <el-input v-model="advancedSearchForm.minInventory" placeholder="最小库存" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="安全库存">
              <el-input v-model="advancedSearchForm.safetyInventory" placeholder="安全库存" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="工艺路线">
              <el-input v-model="advancedSearchForm.processRoute" placeholder="工艺路线" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" class="advanced-search-actions">
            <el-button type="primary" @click="handleAdvancedSearch">查询</el-button>
            <el-button @click="resetAdvancedSearch">重置</el-button>
            <el-button @click="showAdvancedSearch = false">收起</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 列表设置面板 -->
    <div v-show="showColumnSettings" class="column-settings-section">
      <div class="settings-header">
        <h3>列表设置</h3>
        <div class="settings-actions">
          <el-button size="small" type="primary" @click="saveColumnSettings">保存</el-button>
          <el-button size="small" @click="resetColumnSettings">重置</el-button>
        </div>
      </div>
      
      <div class="settings-content">
        <div class="column-visibility">
          <h4>列可见性</h4>
          <div class="column-checkboxes">
            <el-checkbox 
              v-for="column in columnSettings" 
              :key="column.prop"
              v-model="column.visible"
              @change="updateTableColumns"
            >
              {{ column.label }}
            </el-checkbox>
          </div>
        </div>
        
        <div class="column-width">
          <h4>列宽设置</h4>
          <div class="width-inputs">
            <div 
              v-for="column in columnSettings.filter(col => col.visible)" 
              :key="column.prop"
              class="width-input-item"
            >
              <span>{{ column.label }}:</span>
              <el-input-number
                v-model="column.width"
                :min="80"
                :max="300"
                size="small"
                @change="updateTableColumns"
              />
            </div>
          </div>
        </div>
        
        <div class="table-options">
          <h4>表格选项</h4>
          <div class="option-items">
            <el-checkbox v-model="tableOptions.border" @change="updateTableOptions">
              显示边框
            </el-checkbox>
            <el-checkbox v-model="tableOptions.stripe" @change="updateTableOptions">
              斑马纹
            </el-checkbox>
            <el-checkbox v-model="tableOptions.selection" @change="updateTableOptions">
              显示选择框
            </el-checkbox>
          </div>
        </div>
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="table-section">
      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        :border="tableOptions.border"
        :stripe="tableOptions.stripe"
        @selection-change="handleSelectionChange"
        :max-height="600"
      >
        <el-table-column type="selection" width="55" v-if="tableOptions.selection" />
        
        <el-table-column 
          v-if="columnSettings.find(col => col.prop === 'ProductCode')?.visible"
          label="产品编码" 
          prop="ProductCode" 
          :width="columnSettings.find(col => col.prop === 'ProductCode')?.width || 180"
          sortable
          show-overflow-tooltip
        />
        
        <el-table-column 
          v-if="columnSettings.find(col => col.prop === 'ProductName')?.visible"
          label="产品名称" 
          prop="ProductName" 
          :width="columnSettings.find(col => col.prop === 'ProductName')?.width || 150"
          sortable
          show-overflow-tooltip
        />
        
        <el-table-column 
          v-if="columnSettings.find(col => col.prop === 'ProductSpec')?.visible"
          label="产品规格" 
          prop="ProductSpec" 
          :width="columnSettings.find(col => col.prop === 'ProductSpec')?.width || 120"
          sortable
          show-overflow-tooltip
        />
        
        <el-table-column 
          v-if="columnSettings.find(col => col.prop === 'CurrentInventory')?.visible"
          label="库存数量" 
          prop="CurrentInventory" 
          :width="columnSettings.find(col => col.prop === 'CurrentInventory')?.width || 120"
          align="center"
          sortable
        >
          <template #default="{ row }">
            <span :class="{ 'negative-inventory': row.CurrentInventory < 0 }">
              {{ row.CurrentInventory }}
            </span>
          </template>
        </el-table-column>
        
        <el-table-column 
          v-if="columnSettings.find(col => col.prop === 'InventoryUnit')?.visible"
          label="单位" 
          prop="InventoryUnit" 
          :width="columnSettings.find(col => col.prop === 'InventoryUnit')?.width || 80"
          align="center"
        />
        
        <el-table-column 
          v-if="columnSettings.find(col => col.prop === 'ProcessRouteId')?.visible"
          label="工艺路线" 
          prop="ProcessRouteId" 
          :width="columnSettings.find(col => col.prop === 'ProcessRouteId')?.width || 150"
          sortable
          show-overflow-tooltip
        />
        
        <el-table-column 
          v-if="columnSettings.find(col => col.prop === 'MaxInventory')?.visible"
          label="最大库存" 
          prop="MaxInventory" 
          :width="columnSettings.find(col => col.prop === 'MaxInventory')?.width || 120"
          align="center"
          sortable
        />
        
        <el-table-column 
          v-if="columnSettings.find(col => col.prop === 'MinInventory')?.visible"
          label="最小库存" 
          prop="MinInventory" 
          :width="columnSettings.find(col => col.prop === 'MinInventory')?.width || 120"
          align="center"
          sortable
        />
        
        <el-table-column 
          v-if="columnSettings.find(col => col.prop === 'SafetyInventory')?.visible"
          label="安全库存" 
          prop="SafetyInventory" 
          :width="columnSettings.find(col => col.prop === 'SafetyInventory')?.width || 120"
          align="center"
          sortable
        />
        
        <el-table-column 
          v-if="columnSettings.find(col => col.prop === 'ProductAttribute')?.visible"
          label="产品属性" 
          prop="ProductAttribute" 
          :width="columnSettings.find(col => col.prop === 'ProductAttribute')?.width || 100"
          align="center"
        />
        
        <el-table-column 
          v-if="columnSettings.find(col => col.prop === 'CreateTime')?.visible"
          label="创建时间" 
          prop="CreateTime" 
          :width="columnSettings.find(col => col.prop === 'CreateTime')?.width || 160"
          sortable
        >
          <template #default="{ row }">
            {{ formatDateTime(row.CreateTime) }}
          </template>
        </el-table-column>
        
        <el-table-column 
          v-if="columnSettings.find(col => col.prop === 'ModifyTime')?.visible"
          label="修改时间" 
          prop="ModifyTime" 
          :width="columnSettings.find(col => col.prop === 'ModifyTime')?.width || 160"
          sortable
        >
          <template #default="{ row }">
            {{ formatDateTime(row.ModifyTime) }}
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页控件 -->
    <div class="pagination-section">
      <div class="pagination-info">
        <span>共{{ pagination.total }}条</span>
        <el-select 
          v-model="pagination.pageSize" 
          @change="handlePageSizeChange"
          class="page-size-select"
        >
          <el-option label="10条/页" :value="10" />
          <el-option label="20条/页" :value="20" />
          <el-option label="30条/页" :value="30" />
          <el-option label="50条/页" :value="50" />
        </el-select>
      </div>
      
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 30, 50]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handlePageSizeChange"
        @current-change="handleCurrentPageChange"
        class="pagination"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Grid } from '@element-plus/icons-vue'
import { MES_XHY_ApiHost } from '@/utils/Interceptors'
import moment from 'moment'

// 接口类型定义
interface InventoryItem {
  ProductCode: string
  ProductName: string
  ProductSpec: string
  CurrentInventory: number
  InventoryUnit: string
  ProcessRouteId: number
  MaxInventory: number
  MinInventory: number
  SafetyInventory: number
  ProductAttribute: string
  CreateTime: string
  Creator: string
  ModifyTime: string
}

interface ApiResponse {
  totalCount: number
  totalPages: number
  currentPage: number
  pageSize: number
  data: InventoryItem[]
}

interface SearchForm {
  productCode: string
}

interface AdvancedSearchForm {
  productCode: string
  productName: string
  productSpec: string
  inventoryQuantity: string
  inventoryUnit: string
  maxInventory: string
  minInventory: string
  safetyInventory: string
  processRoute: string
}

interface Pagination {
  currentPage: number
  pageSize: number
  total: number
}

// 响应式数据
const loading = ref(false)
const tableData = ref<InventoryItem[]>([])
const selectedRows = ref<InventoryItem[]>([])
const showAdvancedSearch = ref(false)
const showColumnSettings = ref(false) // 新增：控制列表设置面板的显示

// 搜索表单
const searchForm = reactive<SearchForm>({
  productCode: ''
})

// 高级搜索表单
const advancedSearchForm = reactive<AdvancedSearchForm>({
  productCode: '',
  productName: '',
  productSpec: '',
  inventoryQuantity: '',
  inventoryUnit: '',
  maxInventory: '',
  minInventory: '',
  safetyInventory: '',
  processRoute: ''
})

// 分页信息
const pagination = reactive<Pagination>({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 列设置
const columnSettings = ref([
  { prop: 'ProductCode', label: '产品编码', visible: true, width: 180 },
  { prop: 'ProductName', label: '产品名称', visible: true, width: 150 },
  { prop: 'ProductSpec', label: '产品规格', visible: true, width: 120 },
  { prop: 'CurrentInventory', label: '库存数量', visible: true, width: 120 },
  { prop: 'InventoryUnit', label: '单位', visible: true, width: 80 },
  { prop: 'ProcessRouteId', label: '工艺路线', visible: true, width: 150 },
  { prop: 'MaxInventory', label: '最大库存', visible: true, width: 120 },
  { prop: 'MinInventory', label: '最小库存', visible: true, width: 120 },
  { prop: 'SafetyInventory', label: '安全库存', visible: true, width: 120 },
  { prop: 'ProductAttribute', label: '产品属性', visible: true, width: 100 },
  { prop: 'CreateTime', label: '创建时间', visible: true, width: 160 },
  { prop: 'ModifyTime', label: '修改时间', visible: true, width: 160 },
])

// 表格选项
const tableOptions = reactive({
  border: true,
  stripe: true,
  selection: true,
})

// 获取库存余额数据
const fetchInventoryData = async () => {
  loading.value = true
  try {
    const params = {
      pageIndex: pagination.currentPage,
      pageSize: pagination.pageSize,
      ...searchForm
    }
    
    console.log('发送请求参数:', params)
    console.log('请求URL:', '/api/CompletionOrder/GetProductPageList')
    
    const response = await MES_XHY_ApiHost.get('/api/CompletionOrder/GetProductPageList', { params })
    
    console.log('API响应:', response)
    console.log('响应数据:', response.data)
    
    if (response.data) {
      // 检查响应数据结构
      const data = response.data
      console.log('解析后的数据:', data)
      
      // 如果数据在data字段中
      if (data.data && Array.isArray(data.data)) {
        tableData.value = data.data
        pagination.total = data.totalCount || data.total || 0
        pagination.currentPage = data.currentPage || data.current || 1
        pagination.pageSize = data.pageSize || data.size || 10
        console.log('设置表格数据:', tableData.value)
        console.log('设置分页信息:', pagination)
      } 
      // 如果数据在Data字段中（大写）
      else if (data.Data && Array.isArray(data.Data)) {
        tableData.value = data.Data
        pagination.total = data.TotalCount || data.Total || 0
        pagination.currentPage = data.CurrentPage || data.Current || 1
        pagination.pageSize = data.PageSize || data.Size || 10
        console.log('从Data字段设置数据:', tableData.value)
        console.log('设置分页信息:', pagination)
      }
      // 如果数据直接在response.data中
      else if (Array.isArray(data)) {
        tableData.value = data
        pagination.total = data.length
        console.log('直接设置表格数据:', tableData.value)
      }
      // 如果数据在其他字段中
      else if (data.items && Array.isArray(data.items)) {
        tableData.value = data.items
        pagination.total = data.total || data.totalCount || data.items.length
        pagination.currentPage = data.current || data.currentPage || 1
        pagination.pageSize = data.size || data.pageSize || 10
        console.log('从items字段设置数据:', tableData.value)
      }
      else {
        console.warn('未找到有效的数据结构:', data)
        tableData.value = []
        pagination.total = 0
      }
      
      if (tableData.value.length === 0) {
        ElMessage.info('暂无数据')
      } else {
        ElMessage.success(`成功获取${tableData.value.length}条数据`)
      }
    } else {
      console.warn('响应中没有data字段')
      ElMessage.error('获取数据失败')
    }
  } catch (error: any) {
    console.error('获取库存数据失败:', error)
    if (error.response) {
      console.error('错误响应:', error.response)
      console.error('错误状态:', error.response.status)
      console.error('错误数据:', error.response.data)
    }
    ElMessage.error(`网络错误: ${error.message || '请稍后重试'}`)
    tableData.value = []
    pagination.total = 0
    
    // 如果API调用失败，自动显示测试数据
    console.log('API调用失败，显示测试数据')
    // generateTestData() // Removed generateTestData
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  pagination.currentPage = 1
  fetchInventoryData()
}

// 高级搜索处理
const handleAdvancedSearch = () => {
  // 将高级搜索条件合并到搜索表单
  Object.assign(searchForm, advancedSearchForm)
  pagination.currentPage = 1
  fetchInventoryData()
}

// 重置高级搜索
const resetAdvancedSearch = () => {
  Object.keys(advancedSearchForm).forEach(key => {
    advancedSearchForm[key as keyof AdvancedSearchForm] = ''
  })
}

// 重置列设置
const resetColumnSettings = () => {
  columnSettings.value.forEach(col => {
    col.visible = true
    // 重置为默认宽度
    if (col.prop === 'ProductCode') col.width = 180
    else if (col.prop === 'ProductName') col.width = 150
    else if (col.prop === 'ProductSpec') col.width = 120
    else if (col.prop === 'CurrentInventory') col.width = 120
    else if (col.prop === 'InventoryUnit') col.width = 80
    else if (col.prop === 'ProcessRouteId') col.width = 150
    else if (col.prop === 'MaxInventory') col.width = 120
    else if (col.prop === 'MinInventory') col.width = 120
    else if (col.prop === 'SafetyInventory') col.width = 120
    else if (col.prop === 'ProductAttribute') col.width = 100
    else if (col.prop === 'CreateTime') col.width = 160
    else if (col.prop === 'ModifyTime') col.width = 160
  })
  ElMessage.success('列设置已重置')
}

// 更新表格列
const updateTableColumns = () => {
  ElMessage.success('列设置已更新')
}

// 更新表格选项
const updateTableOptions = () => {
  ElMessage.success('表格选项已更新')
}

// 分页大小改变
const handlePageSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  fetchInventoryData()
}

// 当前页改变
const handleCurrentPageChange = (page: number) => {
  pagination.currentPage = page
  fetchInventoryData()
}

// 选择行改变
const handleSelectionChange = (selection: InventoryItem[]) => {
  selectedRows.value = selection
}

// 切换列可见性
const toggleColumnVisibility = () => {
  ElMessage.info('列可见性设置功能开发中...')
}

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '-'
  return moment(dateTime).format('YYYY-MM-DD HH:mm:ss')
}

// 保存列设置
const saveColumnSettings = () => {
  const settingsToSave = columnSettings.value.map(col => ({
    prop: col.prop,
    visible: col.visible,
    width: col.width
  }))
  localStorage.setItem('inventoryBalanceColumnSettings', JSON.stringify(settingsToSave))
  ElMessage.success('列设置已保存')
}

// 加载列设置
const loadColumnSettings = () => {
  const savedSettings = localStorage.getItem('inventoryBalanceColumnSettings')
  if (savedSettings) {
    try {
      const parsedSettings = JSON.parse(savedSettings)
      parsedSettings.forEach((setting: { prop: string; visible: boolean; width: number }) => {
        const col = columnSettings.value.find(cs => cs.prop === setting.prop)
        if (col) {
          col.visible = setting.visible
          col.width = setting.width
        }
      })
      ElMessage.success('列设置已加载')
    } catch (e) {
      console.error('加载列设置失败:', e)
      ElMessage.error('加载列设置失败，请检查本地存储')
    }
  }
}

// 页面加载时获取数据
onMounted(() => {
  fetchInventoryData()
  loadColumnSettings() // 加载保存的列设置
})
</script>

<style scoped>
.inventory-balance {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title-section .page-title {
  margin: 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.search-section {
  display: flex;
  align-items: center;
  gap: 12px;
}

.search-input {
  width: 200px;
}

.search-btn,
.advanced-btn {
  min-width: 80px;
}

.view-toggle-btn {
  padding: 8px 12px;
}

.advanced-search-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
  border: 1px solid #e4e7ed;
}

.advanced-search-form {
  margin-bottom: 0;
}

.advanced-search-actions {
  text-align: center;
  margin-top: 20px;
}

.advanced-search-actions .el-button {
  margin: 0 8px;
}

.column-settings-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
  border: 1px solid #e4e7ed;
}

.settings-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.settings-header h3 {
  margin: 0;
  color: #303133;
  font-size: 18px;
  font-weight: 600;
}

.settings-actions {
  display: flex;
  gap: 10px;
}

.settings-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.column-visibility h4,
.column-width h4,
.table-options h4 {
  margin-bottom: 15px;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.column-checkboxes {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.column-checkboxes .el-checkbox {
  margin-bottom: 10px;
}

.width-inputs {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.width-input-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.width-input-item span {
  font-size: 14px;
  color: #606266;
  min-width: 80px;
}

.option-items {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.option-items .el-checkbox {
  margin-bottom: 10px;
}

.table-section {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
  overflow: hidden;
}

.pagination-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-info {
  display: flex;
  align-items: center;
  gap: 12px;
  color: #606266;
}

.page-size-select {
  width: 120px;
}

.pagination {
  margin: 0;
}

.negative-inventory {
  color: #f56c6c;
  font-weight: bold;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }
  
  .search-section {
    flex-wrap: wrap;
    gap: 8px;
  }
  
  .search-input {
    width: 100%;
    min-width: 200px;
  }
  
  .pagination-section {
    flex-direction: column;
    gap: 16px;
    align-items: center;
  }
}

/* 表格样式优化 */
:deep(.el-table) {
  border-radius: 8px;
}

:deep(.el-table th) {
  background-color: #fafafa;
  color: #303133;
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 12px 0;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: #fafafa;
}

/* 弹窗样式 */
:deep(.el-dialog) {
  border-radius: 8px;
}

:deep(.el-dialog__header) {
  border-bottom: 1px solid #ebeef5;
  padding: 20px 20px 16px;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-dialog__footer) {
  border-top: 1px solid #ebeef5;
  padding: 16px 20px 20px;
}

/* 按钮样式 */
:deep(.el-button) {
  border-radius: 6px;
}

:deep(.el-button--primary) {
  background-color: #409eff;
  border-color: #409eff;
}

:deep(.el-button--primary:hover) {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

/* 输入框样式 */
:deep(.el-input__wrapper) {
  border-radius: 6px;
}

/* 分页样式 */
:deep(.el-pagination) {
  --el-pagination-button-radius: 6px;
}

:deep(.el-pagination .el-pager li) {
  border-radius: 6px;
}
</style>
